<?php
namespace Home\Controller;
use Think\Controller;
class DrawerController extends Controller {
    public function _empty($drawer_id)
    {
        $drawer_id = intval(get_drawer_id($drawer_id));
        if (!$drawer_id) $this->error('对应的抽屉不存在', __APP__);

        $drawer_info = D('drawer')->info($drawer_id);
        if(!is_array($drawer_info)) $this->error('未找到对应的抽屉信息', __APP__);
        $drawer_user_info = D('user')->info($drawer_info['uid']);

        $drawer_goods_list = D('goods')->get_goods_list_by_drawer_id($drawer_id);
        $seo = array(
            'title'       => $drawer_info['title'],
            'keywords'    => $drawer_info['title'],
            'description' => empty($drawer_info['intro']) ? $drawer_info['title'] : $drawer_info['intro']
        );

        $this->assign('drawer_info', $drawer_info);
        $this->assign('seo', $seo);
        $this->assign('drawer_goods_list', $drawer_goods_list);
        $this->assign('drawer_user_info', $drawer_user_info);
        $this->display('index');
    }

    public function index(){
        $uid_str = I('uid', '');
        $uid     = intval(think_decrypt($uid_str));
        if (!$uid) {
            $this->error('用户id错误', __APP__);
        }

        $user_info = D('user')->info($uid);
        if (!is_array($user_info)) {
            $this->error('用户信息不存在', __APP__);
        }


        $this->display();
    }


    /**
     * 创建抽屉
     */
    public function create()
    {
        //需要判断用户是否存在
        $this->display();
    }

    /**
     * 保存抽屉
     */
    public function create_drawer()
    {

        $uid = is_login();
        if(!$uid) {
            $this->error('请先登录', U('User/login'));
        }

        $id          = I('id', 0);
        $title       = I('title', '');
        $intro       = I('intro', '');
        $cover       = I('cover', '');
        $category_id = I('category_id', 0);

        if(!$title) {
            $this->error('抽屉标题必须填写', U('drawer/create'));
        }

        //设置默认封面图片
        if (!$cover && !$id) {
            $cover = 'drawer_default.jpg';
        }

        //判断抽屉是否已经存在
        $drawer_info = D('drawer')->get_drawer_info_by_title($uid, $title);
        if($drawer_info) return $this->error('抽屉已经存在', U('/drawer/'.$drawer_info['id']));

        $drawer_id = D('drawer')->add_drawer($uid, $title, $intro, $cover, $category_id);
        if(!$drawer_id) {
            $this->error('创建抽屉失败', U('drawer/create'));
            return;
        }

        redirect(U('/drawer/'.$drawer_id));
    }

    /**
     * ajax关注抽屉
     */
    public function follow()
    {
        $res = array('status' => 'error', 'msg' => '');
        $user_id = is_login();
        if (!$user_id) {
            $res['msg'] = '您还没有登录，请先登录';
            $this->ajaxReturn($res);
        }

        $drawer_id = I('drawer_id', 0);
        $drawer_info = D('drawer')->info($drawer_id);
        if(!is_array($drawer_info)) {
            $res['msg'] = '未找到对应的抽屉信息';
            $this->ajaxReturn($res);
        };

        $filter = array('drawer_id'=>$drawer_id, 'uid' => $user_id);
        $follow_info = M('drawer_follow_record')->where($filter)->find();

        if (!$follow_info) {
            $filter['add_time'] = date('Y-m-d H:i:s');
            $drawer_res = M('drawer_follow_record')->add($filter);
            //更新抽屉的follow_count数量
            if ($drawer_res) {
                $this->update_drawer_follow_count($drawer_id, 1);
            }

        } else {
            $filter['id']     = $follow_info['id'];
            $filter['status'] = $follow_info['status'] ? 0 : 1;
            $drawer_res = M('drawer_follow_record')->save($filter);
            //更新抽屉的follow_count数量
            if ($drawer_res) {
                $num = $follow_info['status'] ? -1 : 1;
                $this->update_drawer_follow_count($drawer_id, $num);
            }
        }
        $this->ajaxReturn(array('status' => 'succ', 'msg' => '成功'));
    }


    //根据请求方式的不懂自动的返回相关的数据
    private function auto_return($info)
    {
        if(IS_AJAX) {
            return $this->ajaxReturn($info);
        } else {
            return $info;
        }
    }



    private function update_drawer_follow_count($drawer_id, $num)
    {
        if($num < 0) {
            M('drawer')->where('id ='.$drawer_id)->setDec('follow_count', abs($num));
        } else {
            M('drawer')->where('id ='.$drawer_id)->setInc('follow_count', $num);
        }
        return true;
    }


    //通过ajax异步方式创建抽屉
    public function async_create_drawer()
    {
        $res = array('status' => 'fail', 'redirect_url' => '', 'msg' =>'');
        $uid = is_login();
        if(!$uid) {
            $res['msg'] = '请先登录';
            $res['redirect_url'] = __APP__.'/User/login';
            $this->ajaxReturn($res);
        }

        $title = I('title', '');
        $intro = I('intro', '');
        $cover = I('cover', '');
        if(!$title) {
            $res['msg'] = '抽屉标题必须填写';
        }

        //判断抽屉是否已经存在
        $drawer_info = D('drawer')->get_drawer_info_by_title($uid, $title);
        if($drawer_info) {
            $res['status'] = 'succ';
            $res['msg']    = $drawer_info['id'];
            $this->ajaxReturn($res);
        }

        $drawer_id = D('drawer')->add_drawer($uid, $title, $intro, $cover);
        if(!$drawer_id) {
            $res['msg'] = '创建抽屉失败';
        } else {
            $res['status'] = 'succ';
            $res['msg']    = $drawer_id;
        }

        $this->ajaxReturn($res);
    }


    public function drawer_add_goods($drawer_id, $goods_id, $intro)
    {
        $res = array('status' => 'error', 'msg' => '', 'redirect_url'=>'');
        $user_id = is_login();
        if (!$user_id) {
            $res['msg'] = '请先登录';
            $res['redirect_url'] = U('User/login');
            $this->ajaxReturn($res);
        }

        $drawer_info = D('drawer')->info($drawer_id);
        if (!$drawer_info) {
            $res['msg'] = '抽屉信息不存在';
            $this->ajaxReturn($res);
        }

        if ($drawer_info['uid'] != $user_id) {
            $res['msg'] = '您不是这个抽屉的所有者';
            $this->ajaxReturn($res);
        }

        $goods_info = D('goods')->info($goods_id);
        if (!$goods_info) {
            $res['msg'] = '商品信息不存在';
            $this->ajaxReturn($res);
        }

        //@todo 需要将 intro 中的 tag 解析出来

        $filter = array(
            'uid'       => $user_id,
            'drawer_id' => $drawer_id,
            'goods_id'  => $goods_id,
            'status'    => 1
        );
        $drawer_prev_info = M('drawer_goods')->where($filter)->find();
        $info = array(
            'drawer_id' => $drawer_id,
            'uid'       => $user_id,
            'goods_id'  => $goods_id,
            'intro'     => $intro,
            'add_time'  => date("Y-m-d H:i:s")
        );

        //如果之前存在对应的信息的话就更新相关信息
        if ($drawer_prev_info) {
            $info['id'] = $drawer_goods_id = $drawer_prev_info['id'];
            unset($info['add_time']);
            M('drawer_goods')->save($info);
        } else {
            $drawer_goods_id = M('drawer_goods')->add($info);
        }

        if (!$drawer_goods_id) {
            $res['msg'] = '添加商品到抽屉失败';
            $this->ajaxReturn($res);
        }

        $res['status'] = 'succ';
        $res['msg']    = '创建成功';
        $this->ajaxReturn($res);
    }

    /**
     * 上传抽屉封面
     */
    public function upload_cover()
    {
        $upload = new \Think\Upload(); //实例化tp的上传类
        $upload->exts = array('jpg','gif','png','jpeg'); //设置附件上传类型
        $upload->rootPath = './Public/Uploads/'; //相对于站点根目录jd
        $upload->savePath = ''; //设置附件上传目录,地址是相对于根目录(rootPath的)
        //定义空数组，用于存储上传的图片地址
        $datalist = array();

        $info = $upload->upload(); //开始上传
        if(!$info){
            $this->error($upload->getError());
        }else{
            foreach($info as $v) {
                $datalist['goods_id'] = I('goods_id'); //商品id, 通过uplodify插件获取得到

                $pic['cover'] = $v['savepath'].'202_'.$v['savename']; //获取缩略图的文件名
                $pic['img']   = $upload->rootPath.$v['savepath'].$v['savename']; //

                $datalist['cover'] = $pic['cover'];
                $datalist['thumb'] = $pic['thumb'];

                //商品id获取完整的图片地址
                $image = new \Think\Image(); // 利用tp的图片处理类对上传的图片进行处理
                $image->open($pic['img']);

                //获得 202 的封面图片
                $image->thumb(202, 202)->save($upload->rootPath.$v['savepath'].'202_'.$v['savename']); //生成160*160的缩略图

                echo $pic['cover'];
                exit();
            }
        }
    }

    /**
     * 通过用户id获得用户的drawer
     * @param  [type] $uid 用户id
     * @return [type]
     */
    private function get_user_drawer($uid, $num, $offset, $sort='', $order_type = 'ASC')
    {
        $drawer_list = array();
    }
}